import { userLoginApi } from "./../api/api"

// 声明 action.type的值；
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
const ADDUSER = 'ADDUSER'
const DELUSER = 'DELUSER'
const UPDATEUSER = 'UPDATEUSER'
const USERLOGIN = 'USERLOGIN'
const TOKEN = 'TOKEN'

// 创建一个actions的函数，函数一个由type,payload属性的action对象
// 让count增加数量
export const addNum = (count = 1) => ({ type: INCREMENT, payload: count });

// 让count减少数量
export const jianNum = (count = 1) => ({ type: DECREMENT, payload: count });

// 添加用户
// obj = {uname,uage,usex}
export const addUser = (obj) => {
  console.log(obj)
  return { type: ADDUSER, payload: obj }
}
// 删除用户
export const delUser = (uid) => ({ type: DELUSER, payload: uid })
// 更新用户
// obj = {uname,uage,usex,uid}
export const updateUser = (obj) => ({ type: UPDATEUSER, payload: obj });

export const token = (str) => ({ type: TOKEN, payload: str })
// 用户登录,异步的action
export const userLogin = (obj) => {
  // return {type, payload}
  // 异步的action,返回一个异步的函数;
  // 要求给这个异步函数，注入dispatch方法
  return async (dispatch) => {
    userLoginApi(obj).then(res => {
      console.log(res)
      if (res.code === 0) {
        sessionStorage.token = res.token;
        dispatch(token(res.token))

      } else {
        dispatch(token(''))
      }
    })
      .catch(err => {
        console.log('请求接口失败，登录失败')
      })
  }
}